package com.linkhub.oms.component.redis.config.serializer;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

/**
 * @Description: LinkhubRedisConfig
 * @Author: echo
 * @Date: 2024/3/3 11:29
 * @Version: 1.0
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class RedisJsonSerializer {

    public static final Jackson2JsonRedisSerializer<Object> JACKSON_JSON_REDIS_SERIALIZER;


    static{
        JACKSON_JSON_REDIS_SERIALIZER = new Jackson2JsonRedisSerializer<>(Object.class);
        JACKSON_JSON_REDIS_SERIALIZER.setObjectMapper(instanceObjectMapper());
    }

    private static ObjectMapper instanceObjectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        // 设置属性是否可见，这里表示只对成员变量进行序列化/反序列化（其他类型如get方法不作序列化）
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);
        objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
        // 设置序列化成json时，对象的类型（Class名称）与其序列化内容的组合方式，JsonTypeInfo.As.PROPERTY表示与内容为一起作为属性序列化
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
        // 设置序列化时的序列化的内容，JsonInclude.Include.NON_NULL表示只序列化非空属性
        objectMapper.setDefaultPropertyInclusion(JsonInclude.Include.NON_NULL);
        // 设置java8日期类型的序列化与反序列化器
        objectMapper.registerModule(new JavaTimeModule());
        return objectMapper;
    }

}
